// 网络请求工具（Web 版空实现，接口签名与 MerchantApp 对齐）
import { getEnv } from './env.js'

const config = {
  baseURL: getEnv('VUE_APP_BASE_API','http://localhost:6000'),
  timeout: 40000,
  headers: { 'Content-Type': 'application/json' }
}

function buildURL(url, params){ if(!params) return url; const q=Object.keys(params).filter(k=>params[k]!==undefined&&params[k]!==null).map(k=>`${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`).join('&'); return q?`${url}${url.includes('?')?'&':'?'}${q}`:url }

async function request(options){
  const req = { method: 'GET', ...options }
  const baseURL = (req.baseURL!==undefined) ? req.baseURL : config.baseURL
  const finalUrl = baseURL + buildURL(req.url, req.params)
  try{
    const headers = { ...config.headers, ...(req.headers||{}) }
    // 自动附加 Authorization 头（若存在）
    const t = localStorage.getItem('merchant_accessToken') || localStorage.getItem('accessToken')
    if (t && !headers['Authorization']) headers['Authorization'] = `Bearer ${t}`

    const res = await fetch(finalUrl, { method: req.method, headers, body: req.data ? JSON.stringify(req.data) : undefined })

    if(res.status === 401){
      // 未授权：跳转登录页
      if (typeof window !== 'undefined') window.location.href = '/login'
      throw new Error('401 Unauthorized')
    }

    if(!res.ok){ throw new Error(`HTTP ${res.status}`) }
    const data = await res.json().catch(()=>null)
    return data ?? true
  }catch(e){
    if (options?.showError !== false){ console.error('Request error:', e.message||e) }
    throw e
  }
}

export default {
  request,
  get:(url,params,c={})=>request({ url, method:'GET', params, ...c }),
  post:(url,data,c={})=>request({ url, method:'POST', data, ...c }),
  put:(url,data,c={})=>request({ url, method:'PUT', data, ...c }),
  delete:(url,c={})=>request({ url, method:'DELETE', ...c }),
}

